﻿#region Đào Mạnh Hòa
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace GUI.TraLaiNhaCungCap
{
    public partial class frmXuLy : Form
    {
        #region Delegate
        public delegate void GetString(Boolean capnhat);
        public GetString GetData;
        #endregion

        #region khởi tạo
        public bool kiemtra = false;
        bool checkClose = false;
        bool checksua = false;
        Entities.TraLaiNCC temp;
        Entities.TraLaiNCC tralaincc;
        Entities.ChiTietTraLaiNCC[] chitiettralaincc;
        Entities.ChiTietTraLaiNCC[] hienthi;
        Entities.ChiTietTraLaiNCC[] templv;
        Entities.ChiTietTraLaiNCC save;
        Entities.ChiTietHoaDonNhap[] chitiethoadonnhap;
        Entities.ChiTietHoaDonNhap cthdn;
        int i = 0;

        string hanhDong;
        double tongtien = 0;
        string dongia = "0";
        int soluong = 0;
        string thuegtgt = "0";
        double thanhtien = 0;
        double chietkhau = 0;
        string mahanghoa = "";
        string mahoadon = "";
        int soluongconlai = 0;
        public DateTime date;
        string makho = "";
        string tenkho = "";
        double nohienthoi = 0;
        string manhanvien = "";
        double tienboithuong = 0;
        double tienthuegtgt = 0;

        public frmXuLy()
        {
            InitializeComponent();
            try
            {
                date = Entitystatic.date;
                hanhDong = Common.Constants.Insert;

                txtMaNhaCungCap.Focus();

                Entities.CaiDatKho kho = Entitystatic.ViewFile();
                makho = kho.MaKho;
                tenkho = kho.TenKho;
                matralaincc = getID();
                dgvHienThi.DataSource = new Entities.ChiTietTraLaiNCC[0];
                fix();
                //manhanvien = UtilitiesVariable.User.NhanVienID;

            }
            catch
            {
            }
        }

        void fix()
        {
            for (int i = 0; i < dgvHienThi.ColumnCount; i++)
            {
                dgvHienThi.Columns[i].Visible = false;
            }
            dgvHienThi.ReadOnly = true;
            dgvHienThi.Columns[Common.Constants.ChiTietTraLaiNCC.TenHangHoa].Visible = true;
            dgvHienThi.Columns[Common.Constants.ChiTietTraLaiNCC.DonGia].Visible = true;
            dgvHienThi.Columns[Common.Constants.ChiTietTraLaiNCC.MaHoaDon].Visible = true;
            dgvHienThi.Columns[Common.Constants.ChiTietTraLaiNCC.PhanTramChietKhau].Visible = true;
            dgvHienThi.Columns[Common.Constants.ChiTietTraLaiNCC.Thue].Visible = true;
            dgvHienThi.Columns[Common.Constants.ChiTietTraLaiNCC.ThanhTien].Visible = true;
            dgvHienThi.Columns[Common.Constants.ChiTietTraLaiNCC.TenHangHoa].HeaderText = "Tên Hàng Hóa";
            dgvHienThi.Columns[Common.Constants.ChiTietTraLaiNCC.DonGia].HeaderText = "Đơn Giá";
            dgvHienThi.Columns[Common.Constants.ChiTietTraLaiNCC.MaHoaDon].HeaderText = "Mã Hóa Đơn";
            dgvHienThi.Columns[Common.Constants.ChiTietTraLaiNCC.PhanTramChietKhau].HeaderText = "%CK";
            dgvHienThi.Columns[Common.Constants.ChiTietTraLaiNCC.Thue].HeaderText = "%Thue";
            dgvHienThi.Columns[Common.Constants.ChiTietTraLaiNCC.ThanhTien].HeaderText = "Thành Tiền";
            dgvHienThi.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvHienThi.AllowUserToAddRows = false;
            dgvHienThi.AllowUserToDeleteRows = false;
            dgvHienThi.AllowUserToResizeRows = false;
            dgvHienThi.RowHeadersVisible = false;
        }

        public frmXuLy(Entities.TraLaiNCC tralaincc)
        {
            InitializeComponent();
            try
            {
                this.tralaincc = temp = tralaincc;
                hanhDong = Common.Constants.Update;
                tralaincc.HanhDong = hanhDong;
                chitiettralaincc = HienThiChiTiet(temp);
                templv = chitiettralaincc;
                dgvHienThi.DataSource = templv;
                fix();
                XuLyDuLieu(temp);

                txtTongTien.Text = Common.Utilities.FormatMoney(TongTien());
                manhanvien = temp.MaNhanVien;
            }
            catch
            {
            }
        }

        public Entities.ChiTietTraLaiNCC[] HienThiChiTiet(Entities.TraLaiNCC hdbanle)
        {
            try
            {
                Entities.ChiTietTraLaiNCC[] temp = Common.StaticVariable.InterfaceObject.SelectChiTietTraLaiNCC();
                Entities.ChiTietTraLaiNCC[] chitiethdbanle = (Entities.ChiTietTraLaiNCC[])temp.Where(p => p.MaHDTraLaiNCC == hdbanle.MaHDTraLaiNCC).ToArray();
                return chitiethdbanle;
            }
            catch
            {
                return new Entities.ChiTietTraLaiNCC[0];
            }

        }

        #endregion

        #region Ghi Lại
        void GhiLai()
        {
            try
            {
                chitiettralaincc = (Entities.ChiTietTraLaiNCC[])dgvHienThi.DataSource;
                // check object
                if (chitiettralaincc == null || chitiettralaincc.Length == 0)
                {
                    MessageBox.Show(Common.MSG.MSG37(), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    return;
                }
                TinhThue();
                if (tralaincc == null)
                {
                    tralaincc = XuLyObject(Common.Constants.Insert);
                    if (tralaincc == null)
                    {
                        return;
                    }
                }
                if (double.Parse(tralaincc.ThanhToanNgay) == 0)
                {
                    if (MessageBox.Show("Bạn chưa Thanh toán - Bạn có muốn Ghi lại không?", Common.MSG.TieuDe, MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.No)
                    {
                        return;
                    }
                }
                // check conflic insert
                if (!CheckConflicInsert(tralaincc))
                {
                    MessageBox.Show(Common.MSG.MSG5(tralaincc.MaHDTraLaiNCC), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    GetData(true);
                    tralaincc.MaHDTraLaiNCC = matralaincc;
                    foreach (Entities.ChiTietTraLaiNCC item in chitiettralaincc)
                    {
                        item.MaHDTraLaiNCC = matralaincc;
                    }
                    return;
                }

                Entities.ChiTietHoaDonNhap[] ct = CheckHoaDonNhap(chitiettralaincc);
                Entities.PhieuTTNCC pt = CheckPhieuTTNCC(tralaincc);
                Entities.ChiTietPhieuTTNCC[] ctpt = CheckChiTietPhieuTTNCC(tralaincc, pt);
                tralaincc.ChiTietHoaDonNhap = ct;
                tralaincc.ChiTietTraLaiNCC = chitiettralaincc;
                tralaincc.PhieuTTNCC = pt;
                tralaincc.ChiTietPhieuTTNCC = ctpt;
                // check insert
                tralaincc.TaiKhoan = UtilitiesVariable.User;
                if (Common.StaticVariable.InterfaceObject.InsertUpdateTraLaiNCC(tralaincc) == 0)
                {
                    MessageBox.Show(Common.MSG.MSG15(tralaincc.MaHDTraLaiNCC), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    return;
                }
                checkClose = true;
                this.Close();

            }
            catch
            {
            }
        }

        Entities.ChiTietHoaDonNhap[] CheckHoaDonNhap(Entities.ChiTietTraLaiNCC[] chitiettralaincc)
        {
            try
            {
                Entities.ChiTietHoaDonNhap ctt = new Entities.ChiTietHoaDonNhap();
                ctt.HanhDong = "1";
                ctt.MaHoaDonNhap = mahoadon;
                ctt.MaHangHoa = "";
                Entities.ChiTietHoaDonNhap[] cthdn = new TimKiem.frmHangHoaNhapKho().HienThi(ctt);
                Entities.ChiTietHoaDonNhap[] ct = new Entities.ChiTietHoaDonNhap[chitiettralaincc.Length];
                int sotang = 0;
                foreach (Entities.ChiTietTraLaiNCC item in chitiettralaincc)
                {
                    foreach (Entities.ChiTietHoaDonNhap item1 in cthdn)
                    {
                        if (item.MaHangHoa.ToUpper() == item1.MaHangHoa.ToUpper() && item.MaHoaDon == item1.MaHoaDonNhap)
                        {
                            ct[sotang] = item1;
                            ct[sotang].SoLuongConLai = item1.SoLuongConLai - item.SoLuong;
                            ct[sotang].MaHangHoa = item.MaHangHoa.ToUpper();
                            sotang++;
                        }
                    }
                }
                return ct;
            }
            catch
            {
                return new Entities.ChiTietHoaDonNhap[0];
            }
        }

        Entities.PhieuTTNCC CheckPhieuTTNCC(Entities.TraLaiNCC tralaincc)
        {
            try
            {
                Entities.PhieuTTNCC pt = new Entities.PhieuTTNCC();
                pt.HanhDong = Common.Constants.Insert;
                pt.MaPhieuTTNCC = new PhieuTTNCC.frmXuLy("").getID();
                pt.NgayLap = DateTime.Parse(date.ToString("MM/dd/yyyy"));
                pt.MaNhaCungCap = tralaincc.MaNCC;
                pt.TenNhaCungCap = tralaincc.TenNCC;
                pt.TongThanhToan = tralaincc.ThanhToanNgay;
                pt.NoHienThoi = tralaincc.NoHienThoi;
                pt.LoaiPhieu = false;
                pt.Nguoinhan = "";
                pt.MaNhanVien = "";
                pt.GhiChu = "";
                pt.Deleted = false;
                //pt.TaiKhoan = UtilitiesVariable.User;
                return pt;
            }
            catch
            {
                return null;
            }
        }
        Entities.ChiTietPhieuTTNCC[] CheckChiTietPhieuTTNCC(Entities.TraLaiNCC tralaincc, Entities.PhieuTTNCC phieuttncc)
        {
            try
            {
                List<Entities.ChiTietPhieuTTNCC> array = new List<Entities.ChiTietPhieuTTNCC>();
                Entities.ChiTietPhieuTTNCC[] ctpttncc = new Entities.ChiTietPhieuTTNCC[2];

                ctpttncc[0] = new Entities.ChiTietPhieuTTNCC();
                ctpttncc[0].HanhDong = Common.Constants.Insert;
                ctpttncc[0].MaHoaDonNhap = tralaincc.MaHDTraLaiNCC;
                ctpttncc[0].MaPhieuTTNCC = phieuttncc.MaPhieuTTNCC;
                ctpttncc[0].ThanhToan = tralaincc.ThanhToanNgay;
                ctpttncc[0].TongTienThanhToan = tralaincc.TienBoiThuong;
                ctpttncc[0].SoNo = (double.Parse(tralaincc.TienBoiThuong) - double.Parse(tralaincc.ThanhToanNgay) - double.Parse(tralaincc.ThanhToanSauKhiLapPhieu)).ToString();
                ctpttncc[0].GhiChu = "";

                ctpttncc[0].Deleted = false;
                array.Add(ctpttncc[0]);
                ctpttncc = (Entities.ChiTietPhieuTTNCC[])array.ToArray();
                return ctpttncc;
            }
            catch
            {
                return null;
            }
        }
        #endregion

        #region Check Conflic Insert
        string matralaincc;
        public bool CheckConflicInsert(Entities.TraLaiNCC tralaincc)
        {
            matralaincc = getID();
            if (tralaincc.MaHDTraLaiNCC == matralaincc)
            {
                return true;
            }
            return false;
        }
        #endregion

        #region Thanh Toán
        void ThanhToan()
        {
            chitiettralaincc = (Entities.ChiTietTraLaiNCC[])dgvHienThi.DataSource;
            // check object
            if (chitiettralaincc == null || chitiettralaincc.Length == 0)
            {
                MessageBox.Show(Common.MSG.MSG37(), Common.MSG.TieuDe, MessageBoxButtons.OK);
                return;
            }
            if (tralaincc == null)
            {
                tralaincc = XuLyObject(Common.Constants.Insert);
                if (tralaincc == null)
                {
                    return;
                }
            }

            frmThanhToan xuly = new frmThanhToan(tralaincc);
            xuly.ShowDialog();
            if (!frmThanhToan.kiemtra)
            {
                if (hanhDong == Common.Constants.Insert)
                    tralaincc = frmThanhToan.tralaincc;
            }
            frmThanhToan.kiemtra = false;
        }
        #endregion

        #region in
        void In()
        {
        }
        #endregion

        #region Thoát
        void Thoat()
        {
            kiemtra = true;
            this.Close();
        }
        #endregion

        #region xử lý id
        public string getID()
        {
            try
            {
                string str = "";
                Entities.GetID layid = new Entities.GetID();
                layid.MaKho = makho;
                layid.Ngay = date.ToString("MM/dd/yyyy");
                Entities.GetID lay = Common.StaticVariable.InterfaceObject.GetIDTraLaiNCC(layid);
                if (lay.ColumnName == null)
                {
                    str = "TLNCC/" + Common.Utilities.GetDateID(date.ToString("dd/MM/yyyy")) + "_0001";
                }
                else
                {
                    str = lay.ColumnName;
                    str = Common.Utilities.ProcessID(str);
                }

                return str;
            }
            catch
            {
                return "TLNCC/" + Common.Utilities.GetDateID(date.ToString("dd/MM/yyyy")) + "_0001";
            }
        }
        #endregion

        #region validate
        public bool Validat()
        {
            try
            {
                if (txtMaNhaCungCap.Text == "<F4 - Tra cứu>" || txtMaNhaCungCap.Text.Length == 0)
                {
                    MessageBox.Show(Common.MSG.MSG13(lbMaNhaCungCap.Text), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    txtMaNhaCungCap.Focus();
                    return false;
                }
                if (txtNguoiNhan.Text.Length == 0)
                {
                    MessageBox.Show(Common.MSG.MSG13(lblNguoiNhan.Text), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    txtNguoiNhan.Focus();
                    return false;
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        public bool ValidateDetails()
        {
            try
            {
                if (txtMaHangHoa.Text == "<F4 - Tra cứu>" || txtMaHangHoa.Text.Length == 0)
                {
                    MessageBox.Show(Common.MSG.MSG13(lbMaHangHoa.Text), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    txtMaHangHoa.Focus();
                    return false;
                }
                if (txtSoLuong.Text.Length == 0 || txtSoLuong.Text == "0")
                {
                    MessageBox.Show(Common.MSG.MSG22("Số lượng"), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    txtSoLuong.Focus();
                    return false;
                }
                if (txtTenHangHoa.Text.Length == 0)
                {
                    MessageBox.Show(Common.MSG.MSG13(lbMaHangHoa.Text), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    txtSoLuong.Focus();
                    return false;
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        #endregion

        #region xử lý object

        public void XuLyDuLieu(Entities.TraLaiNCC tralaincc)
        {
            try
            {
                matralaincc = tralaincc.MaHDTraLaiNCC;
                manhanvien = tralaincc.MaNhanVien;
                date = tralaincc.Ngaytra.Date;
                txtMaNhaCungCap.Text = tralaincc.MaNCC;
                txtTenNhaCungCap.Text = tralaincc.TenNCC;
                nohienthoi = double.Parse(tralaincc.NoHienThoi);
                txtNguoiNhan.Text = tralaincc.NguoiNhanHang;
                makho = tralaincc.MaKho;
                tenkho = tralaincc.TenKho;
                txtGhiChu.Text = tralaincc.GhiChu;
            }
            catch
            {
            }
        }

        public Entities.TraLaiNCC XuLyObject(string hanhDong)
        {
            try
            {
                if (Validat())
                {
                    Entities.TraLaiNCC tralaincc = new Entities.TraLaiNCC();
                    tralaincc.HanhDong = hanhDong;
                    tralaincc.MaHDTraLaiNCC = matralaincc;
                    tralaincc.MaNhanVien = manhanvien;
                    tralaincc.Ngaytra = date.Date;
                    tralaincc.MaNCC = txtMaNhaCungCap.Text;
                    tralaincc.TenNCC = txtTenNhaCungCap.Text;
                    tralaincc.NoHienThoi = nohienthoi.ToString();
                    tralaincc.NguoiNhanHang = txtNguoiNhan.Text;
                    tralaincc.MaKho = makho;
                    tralaincc.TenKho = tenkho;
                    tralaincc.TienBoiThuong = tienboithuong.ToString();
                    tralaincc.ThanhToanNgay = "0";
                    tralaincc.ThanhToanSauKhiLapPhieu = "0";
                    tralaincc.ThueGTGT = tienthuegtgt.ToString();
                    tralaincc.Deleted = false;
                    tralaincc.GhiChu = txtGhiChu.Text;
                    return tralaincc;
                }
                return null;
            }
            catch
            {
                return null;
            }
        }
        #endregion

        #region xử lý list view
        void TinhThue()
        {
            tienthuegtgt = 0;
            foreach (Entities.ChiTietTraLaiNCC item in templv)
            {
                double dongiadachietkhau = (double.Parse(item.DonGia) - (double.Parse(item.DonGia) * double.Parse(item.PhanTramChietKhau)));
                double thanhtien = item.SoLuong * dongiadachietkhau;
                tienthuegtgt += (thanhtien) * double.Parse(item.Thue);
            }
        }

        string TongTien()
        {
            try
            {
                tongtien = 0;
                foreach (Entities.ChiTietTraLaiNCC item in templv)
                {
                    tongtien += double.Parse(item.ThanhTien);
                }
                tienboithuong = tongtien;
                return tongtien.ToString();
            }
            catch
            {
                return tongtien.ToString();
            }
        }
        #endregion

        #region thêm row
        void AddRow()
        {
            if (hanhDong != Common.Constants.Insert) return;
            {
                try
                {
                    if (!checksua)
                    {
                        dongia = cthdn.DonGia;
                        chietkhau = double.Parse(cthdn.PhanTramChietKhau);
                        thuegtgt = cthdn.Thue;
                        soluong = int.Parse(txtSoLuong.Text);

                        if (mahoadon == "")
                        {
                            mahoadon = cthdn.MaHoaDonNhap;
                        }
                    }
                    else
                    {
                        soluong = int.Parse(txtSoLuong.Text);
                    }
                    int sohangtrongbang;
                    hienthi = (Entities.ChiTietTraLaiNCC[])dgvHienThi.DataSource;
                    // list view = null
                    if (hienthi == null)
                    {
                        templv = new Entities.ChiTietTraLaiNCC[1];

                        double dongiadachietkhau = (double.Parse(dongia)) - (((double.Parse(dongia)) * chietkhau) / 100);
                        double thuegtgtdachietkhau = (dongiadachietkhau * double.Parse(thuegtgt)) / 100;
                        thanhtien = ((dongiadachietkhau + thuegtgtdachietkhau) * soluong);
                        templv[0] = new Entities.ChiTietTraLaiNCC(Common.Constants.Insert, 0, matralaincc, txtMaHangHoa.Text, txtTenHangHoa.Text, mahoadon,
                            soluong, chietkhau.ToString(), Common.Utilities.FormatMoney(dongia),
                            Common.Utilities.FormatMoney(thanhtien.ToString()), thuegtgt, "", false, makho);
                        dgvHienThi.DataSource = templv;
                        fix();
                        return;
                    }

                    sohangtrongbang = hienthi.Length;
                    // số lượng bảng ghi khác 0
                    if (sohangtrongbang != 0)
                    {
                        for (int j = 0; j < sohangtrongbang; j++)
                        {
                            // nếu tìm được mã đã có trong list view
                            if (mahanghoa.ToUpper() == hienthi[j].MaHangHoa.ToUpper() && mahoadon == hienthi[j].MaHoaDon)
                            {
                                templv = new Entities.ChiTietTraLaiNCC[sohangtrongbang];
                                break;
                            }
                            // nếu không tìm được
                            else
                                templv = new Entities.ChiTietTraLaiNCC[sohangtrongbang + 1];
                        }
                    }
                    // số lượng bảng ghi = 0
                    else
                        templv = new Entities.ChiTietTraLaiNCC[sohangtrongbang + 1];
                    // nếu số lượng bảng ghi khác 0
                    if (templv.Length != 0)
                    {
                        try
                        {
                            // số lượng bảng ghi = số lượng row list view
                            if (templv.Length == hienthi.Length)
                            {
                                SoLuongBangSoLuong(templv, hienthi);
                            }
                            // số lượng bảng ghi không = số lượng row list view
                            else
                            {
                                SoLuongKhacSoLuong(templv, hienthi);
                            }
                        }
                        catch
                        {
                            double dongiadachietkhau = (double.Parse(dongia)) - (((double.Parse(dongia)) * chietkhau) / 100);
                            double thuegtgtdachietkhau = (dongiadachietkhau * double.Parse(thuegtgt)) / 100;
                            thanhtien = (dongiadachietkhau + thuegtgtdachietkhau) * soluong;

                            templv[templv.Length - 1] = new Entities.ChiTietTraLaiNCC(Common.Constants.Insert, 0, matralaincc, txtMaHangHoa.Text, txtTenHangHoa.Text, mahoadon,
                                                soluong, chietkhau.ToString(), dongia, thanhtien.ToString(), thuegtgt, "", false, makho);
                        }
                        dgvHienThi.DataSource = templv;
                        fix();
                    }
                }
                catch
                {
                    return;
                }
                finally
                {
                    checksua = false;
                    txtSoLuong.Text = "";
                    soluong = 1;
                    mahanghoa = "";
                    mahoadon = "";
                    cthdn = null;
                    txtMaHangHoa.Text = "";
                    txtTenHangHoa.Text = "";
                    txtMaHangHoa.Focus();
                    dongia = "0";
                    chietkhau = 0;
                    thuegtgt = "0";
                    thanhtien = 0;
                    txtTongTien.Text = Common.Utilities.FormatMoney(TongTien());
                }
            }
        }

        void SoLuongBangSoLuong(Entities.ChiTietTraLaiNCC[] templv, Entities.ChiTietTraLaiNCC[] hienthi)
        {
            for (int j = 0; j < templv.Length; j++)
            {
                // nếu mã = mã trong list view
                if (mahanghoa.ToUpper() == hienthi[j].MaHangHoa.ToUpper() && mahoadon == hienthi[j].MaHoaDon)
                {
                    int soluongcu = hienthi[j].SoLuong;
                    int soluonghientai = soluongcu + soluong;

                    double dongiadachietkhau = (double.Parse(dongia)) - (((double.Parse(dongia)) * chietkhau) / 100);
                    double thuegtgtdachietkhau = (dongiadachietkhau * double.Parse(thuegtgt)) / 100;
                    thanhtien = (dongiadachietkhau + thuegtgtdachietkhau) * soluonghientai;

                    templv[j] = new Entities.ChiTietTraLaiNCC(Common.Constants.Insert, 0, matralaincc, txtMaHangHoa.Text.ToUpper(), txtTenHangHoa.Text, mahoadon,
                            soluonghientai, chietkhau.ToString(),
                            Common.Utilities.FormatMoney(dongia), Common.Utilities.FormatMoney(thanhtien.ToString())
                            , thuegtgt, "", false, makho);

                }
                // nếu mã không = mã trong list view
                else
                    templv[j] = new Entities.ChiTietTraLaiNCC(Common.Constants.Insert, 0, matralaincc, hienthi[j].MaHangHoa.ToUpper(), hienthi[j].TenHangHoa, hienthi[j].MaHoaDon,
                 hienthi[j].SoLuong, hienthi[j].PhanTramChietKhau, hienthi[j].DonGia, hienthi[j].ThanhTien, hienthi[j].Thue, "", false, makho);

            }
        }

        void SoLuongKhacSoLuong(Entities.ChiTietTraLaiNCC[] templv, Entities.ChiTietTraLaiNCC[] hienthi)
        {
            for (int j = 0; j < templv.Length; j++)
            {
                // lấy lại số bảng ghi trên list view
                if (j < templv.Length - 1)
                    templv[j] = new Entities.ChiTietTraLaiNCC(Common.Constants.Insert, 0, matralaincc, hienthi[j].MaHangHoa.ToUpper(), hienthi[j].TenHangHoa, hienthi[j].MaHoaDon,
                 hienthi[j].SoLuong, hienthi[j].PhanTramChietKhau, hienthi[j].DonGia, hienthi[j].ThanhTien, hienthi[j].Thue, "", false, makho);
                // bảng ghi cuối cùng là mới insert vào
                else
                {
                    double dongiadachietkhau = (double.Parse(dongia)) - (((double.Parse(dongia)) * chietkhau) / 100);
                    double thuegtgtdachietkhau = (dongiadachietkhau * double.Parse(thuegtgt)) / 100;
                    thanhtien = (dongiadachietkhau + thuegtgtdachietkhau) * soluong;
                    templv[templv.Length - 1] = new Entities.ChiTietTraLaiNCC(Common.Constants.Insert, 0, matralaincc, txtMaHangHoa.Text, txtTenHangHoa.Text, mahoadon,
                            soluong, chietkhau.ToString(), Common.Utilities.FormatMoney(dongia)
                            , Common.Utilities.FormatMoney(thanhtien.ToString()), thuegtgt, "", false, makho);
                }

            }
        }

        #endregion

        #region sửa row
        void SuaRow()
        {
            if (hanhDong != Common.Constants.Insert) return;
            {
                try
                {
                    // obj = null
                    if (save == null)
                    {
                        return;
                    }
                    hienthi = (Entities.ChiTietTraLaiNCC[])dgvHienThi.DataSource;
                    // list view = null
                    if (hienthi == null)
                    {
                        return;
                    }
                    checksua = true;
                    templv = new Entities.ChiTietTraLaiNCC[hienthi.Length - 1];
                    int sotang = 0;
                    for (int j = 0; j < hienthi.Length; j++)
                    {
                        if (hienthi[j].MaHangHoa.ToUpper() != save.MaHangHoa.ToUpper() || hienthi[j].MaHoaDon != save.MaHoaDon)
                        {
                            templv[sotang] = new Entities.ChiTietTraLaiNCC(Common.Constants.Insert, 0, matralaincc, hienthi[j].MaHangHoa.ToUpper(), hienthi[j].TenHangHoa, hienthi[j].MaHoaDon,
                                     hienthi[j].SoLuong, hienthi[j].PhanTramChietKhau, hienthi[j].DonGia, hienthi[j].ThanhTien, hienthi[j].Thue, "", false, makho);
                            sotang++;
                        }
                        else
                        {
                            txtSoLuong.Text = hienthi[j].SoLuong.ToString();
                            txtTenHangHoa.Text = hienthi[j].TenHangHoa;
                            txtMaHangHoa.Text = mahanghoa = hienthi[j].MaHangHoa;
                            dongia = hienthi[j].DonGia;
                            chietkhau = double.Parse(hienthi[j].PhanTramChietKhau);
                            thuegtgt = hienthi[j].Thue;
                            mahoadon = hienthi[j].MaHoaDon;
                            soluong = hienthi[j].SoLuong;
                        }
                    }
                    dgvHienThi.DataSource = templv;
                    fix();
                    save = null;
                    txtSoLuong.Focus();
                    txtSoLuong.SelectAll();

                }
                catch
                {
                }
                finally
                {
                    txtTongTien.Text = Common.Utilities.FormatMoney(TongTien());
                    txtSoLuong.Focus();
                    txtSoLuong.SelectAll();
                }
            }
        }
        #endregion

        #region thêm Nhà Cung Cấp
        void ThemNhaCungCap()
        {
            try
            {
                if (hanhDong != Common.Constants.Insert) return;
                if (makho.Length == 0 || makho == "NULL")
                {
                    MessageBox.Show(Common.MSG.MSG28(), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    return;
                }
                if (txtMaNhaCungCap.Text != "<F4 - Tra cứu>" && txtMaNhaCungCap.Text.Length != 0)
                {
                    if (MessageBox.Show(Common.MSG.MSG36(), Common.MSG.TieuDe, MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                    {
                        string manhacungcap = txtMaNhaCungCap.Text;
                        templv = null;
                        dgvHienThi.DataSource = templv;
                        fix();
                        txtMaHangHoa.Text = txtMaHoaDon.Text = "<F4 - Tra cứu>";
                        txtSoLuong.Text = "";
                        txtTenHangHoa.Text = txtTenNhaCungCap.Text = "";
                        soluong = 1;
                        mahanghoa = "";
                        mahoadon = "";
                        cthdn = null;
                        dongia = "0";
                        chietkhau = 0;
                        thuegtgt = "0";
                        thanhtien = 0;
                        checksua = false;
                        nohienthoi = 0;
                    }
                    else
                    {
                        return;
                    }
                }

                TimKiem.frmTimKiemNCC frm = new TimKiem.frmTimKiemNCC();
                frm.ShowDialog();
                // chechk object
                if (TimKiem.frmTimKiemNCC.NhaCungCap == null)
                {
                    return;
                }
                // gán giá trị
                txtMaNhaCungCap.Text = TimKiem.frmTimKiemNCC.NhaCungCap.MaNhaCungCap;
                txtTenNhaCungCap.Text = TimKiem.frmTimKiemNCC.NhaCungCap.TenNhaCungCap;
                nohienthoi = double.Parse(TimKiem.frmTimKiemNCC.NhaCungCap.DuNo);
                TimKiem.frmTimKiemNCC.NhaCungCap = null;
                txtNguoiNhan.Focus();
            }
            catch
            {
            }
        }
        #endregion

        #region thêm Hóa đơn
        void ThemHoaDon()
        {
            try
            {
                if (hanhDong != Common.Constants.Insert) return;
                if (txtMaNhaCungCap.Text == "<F4 - Tra cứu>" || txtMaNhaCungCap.Text.Length == 0)
                {
                    MessageBox.Show(Common.MSG.MSG13(lbMaNhaCungCap.Text), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    txtMaNhaCungCap.Focus();
                    return;
                }
                if (makho.Length == 0 || makho == "NULL")
                {
                    MessageBox.Show(Common.MSG.MSG28(), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    return;
                }



                TimKiem.frmNhapKho frm = new TimKiem.frmNhapKho(txtMaNhaCungCap.Text, makho);
                frm.ShowDialog();
                // chechk object
                if (TimKiem.frmNhapKho.hoadonnhap == null)
                {
                    return;
                }
                // gán giá trị
                txtMaHoaDon.Text = mahoadon = TimKiem.frmNhapKho.hoadonnhap.MaHoaDonNhap;
                TimKiem.frmNhapKho.hoadonnhap = null;
                txtGhiChu.Focus();

                txtMaHangHoa.Text = "<F4 - Tra cứu>";
                txtSoLuong.Text = "";
                txtTenHangHoa.Text = "";
                soluong = 1;
                mahanghoa = "";
                mahoadon = "";
                cthdn = null;
                dongia = "0";
                chietkhau = 0;
                thuegtgt = "0";
                thanhtien = 0;
                checksua = false;
            }
            catch
            {
            }
        }
        #endregion

        #region thêm Hàng Hóa
        void CheckSoLuongConLai()
        {
            try
            {
                chitiettralaincc = (Entities.ChiTietTraLaiNCC[])dgvHienThi.DataSource;

                foreach (Entities.ChiTietTraLaiNCC item in chitiettralaincc)
                {
                    if (item.MaHangHoa.ToUpper() == mahanghoa && item.MaHoaDon == mahoadon)
                    {
                        soluongconlai = soluongconlai - item.SoLuong;
                        return;
                    }
                }
            }
            catch
            {
            }
        }
        void ThemHangHoa()
        {
            try
            {
                if (hanhDong != Common.Constants.Insert) return;
                if (makho.Length == 0 || makho == "NULL")
                {
                    MessageBox.Show(Common.MSG.MSG28(), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    return;
                }

                if (txtMaNhaCungCap.Text == "<F4 - Tra cứu>" || txtMaNhaCungCap.Text.Length == 0)
                {
                    MessageBox.Show(Common.MSG.MSG13(lbMaNhaCungCap.Text), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    txtMaNhaCungCap.Focus();
                    return;
                }

                if (txtMaHoaDon.Text == "<F4 - Tra cứu>" || txtMaHoaDon.Text.Length == 0)
                {
                    MessageBox.Show(Common.MSG.MSG13(lbMaHoaDon.Text), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    txtMaHoaDon.Focus();
                    return;
                }
                Entities.ChiTietHoaDonNhap ct = new Entities.ChiTietHoaDonNhap();
                ct.HanhDong = "4";
                ct.MaHoaDonNhap = txtMaHoaDon.Text;
                ct.MaHangHoa = "";
                TimKiem.frmHangHoaNhapKho frm = new TimKiem.frmHangHoaNhapKho(ct);
                frm.ShowDialog();
                // chechk object
                if (TimKiem.frmHangHoaNhapKho.chitiethoadonnhap == null)
                {
                    cthdn = null;
                    return;
                }
                // gán giá trị
                txtMaHangHoa.Text = mahanghoa = TimKiem.frmHangHoaNhapKho.chitiethoadonnhap.MaHangHoa.ToUpper();
                txtTenHangHoa.Text = TimKiem.frmHangHoaNhapKho.chitiethoadonnhap.TenHangHoa;
                soluongconlai = TimKiem.frmHangHoaNhapKho.chitiethoadonnhap.SoLuongConLai;
                mahoadon = TimKiem.frmHangHoaNhapKho.chitiethoadonnhap.MaHoaDonNhap;
                cthdn = TimKiem.frmHangHoaNhapKho.chitiethoadonnhap;
                TimKiem.frmHangHoaNhapKho.chitiethoadonnhap = null;
                CheckSoLuongConLai();
                txtSoLuong.Focus();
                checksua = false;
                if (chitiethoadonnhap == null)
                {
                    chitiethoadonnhap = new TimKiem.frmHangHoaNhapKho().HienThi(ct);
                }
            }
            catch
            {
            }

        }
        #endregion

        #region xử lý thêm sửa
        void XuLyThemSua()
        {
            if (hanhDong == Common.Constants.Insert)
                GhiLai();
            else
                MessageBox.Show("Không thể sửa Hóa đơn trả lại nhà cung cấp", Common.MSG.TieuDe, MessageBoxButtons.OK);
        }
        #endregion

        #region Event
        private void frmXuLy_Load(object sender, EventArgs e)
        {
            lblTenNhanVien.Text = UtilitiesVariable.User.TenDangNhap;
            this.FormClosing += new FormClosingEventHandler(frmXuLy_FormClosing);
            btnGhiLai.Click += new EventHandler(btnGhiLai_Click);
            btnThemGV.Click += new EventHandler(btnThemGV_Click);
            btnThanhToan.Click += new EventHandler(btnThanhToan_Click);
            btnThoat.Click += new EventHandler(btnThoat_Click);
            btnTimNCC.Click += new EventHandler(btnTimNCC_Click);
            dgvHienThi.CellClick += new DataGridViewCellEventHandler(dgvHienThi_CellClick);
            dgvHienThi.CellDoubleClick += new DataGridViewCellEventHandler(dgvHienThi_CellDoubleClick);
            dgvHienThi.KeyDown += new KeyEventHandler(dgvHienThi_KeyDown);
            txtMaHoaDon.KeyDown += new KeyEventHandler(txt_KeyDown);
            txtMaHangHoa.KeyDown += new KeyEventHandler(txt_KeyDown);
            txtSoLuong.KeyDown += new KeyEventHandler(txt_KeyDown);
            txtMaNhaCungCap.KeyDown += new KeyEventHandler(txt_KeyDown);
            txtSoLuong.TextChanged += new EventHandler(txtSoLuong_TextChanged);
        }

        void txtSoLuong_TextChanged(object sender, EventArgs e)
        {
            try
            {
                int i = int.Parse(txtSoLuong.Text);
                if (i > soluongconlai)
                {
                    txtSoLuong.Text = soluongconlai.ToString();
                    MessageBox.Show("Số lượng trả lại không thể lơn hơn Số lượng hàng mua",Common.MSG.TieuDe);
                }
                if (i == 0)
                {
                    txtSoLuong.Text = "";
                }
            }
            catch
            {
                txtSoLuong.Text = "";
            }
        }

        void btnGhiLai_Click(object sender, EventArgs e)
        {
            GhiLai();
        }
        
        void dgvHienThi_KeyDown(object sender, KeyEventArgs e)
        {
            if (hanhDong != Common.Constants.Insert)
                return;
            if (i < 0)
                return;
            if (dgvHienThi.RowCount == 0)
                return;
            save = ((Entities.ChiTietTraLaiNCC[])dgvHienThi.DataSource)[i];

            switch (e.KeyData)
            {
                case Keys.Enter:
                    {
                        SuaRow();
                        break;
                    }
            }
        }

        void txt_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                switch (e.KeyData)
                {
                    case Keys.F4:
                        {
                            TextBox tx = (TextBox)sender;
                            switch (tx.Name)
                            {
                                case Common.Constants.TraLaiNCC.txtMaHangHoa:
                                    {
                                        ThemHangHoa();
                                        break;
                                    }
                                case Common.Constants.TraLaiNCC.txtMaNhaCungCap:
                                    {
                                        ThemNhaCungCap();
                                        break;
                                    }
                                case Common.Constants.TraLaiNCC.txtMaHoaDon:
                                    {
                                        ThemHoaDon();
                                        break;
                                    }
                            }
                            break;
                        }
                    case Keys.Enter:
                        {
                            TextBox tx = (TextBox)sender;
                            try
                            {
                                TextBox temp = (TextBox)sender;
                                XuLyEnter(temp.Name);
                            }
                            catch
                            {

                            }
                            break;
                        }
                }
            }
            catch
            {
            }
        }

        void XuLyEnter(string hanhDong)
        {
            try
            {
                switch (hanhDong)
                {
                    case Common.Constants.TraLaiNCC.txtMaNhaCungCap:
                        {
                            txtNguoiNhan.Focus();
                            break;
                        }
                    case Common.Constants.TraLaiNCC.txtMaHangHoa:
                        {
                            XuLyEnter_MaHangHoa();
                            break;
                        }
                    case Common.Constants.TraLaiNCC.txtMaHoaDon:
                        {
                            txtGhiChu.Focus();
                            break;
                        }
                    case Common.Constants.TraLaiNCC.txtSoLuong:
                        {
                            if (ValidateDetails())
                            {
                                XuLyEnter_SoLuong();
                            }
                            break;
                        }
                    case Common.Constants.TraLaiNCC.txtNguoiNhan:
                        {
                            txtMaHoaDon.Focus();
                            break;
                        }
                    case Common.Constants.TraLaiNCC.txtGhiChu:
                        {
                            txtMaHangHoa.Focus();
                            break;
                        }
                    default:
                        break;
                }
            }
            catch
            {
            }
        }

        void XuLyEnter_MaHangHoa()
        {
            try
            {
                if (txtMaNhaCungCap.Text == "<F4 - Tra cứu>" || txtMaNhaCungCap.Text.Length == 0)
                {
                    MessageBox.Show(Common.MSG.MSG13(lbMaNhaCungCap.Text), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    txtMaNhaCungCap.Focus();
                    return;
                }

                if (txtMaHoaDon.Text == "<F4 - Tra cứu>" || txtMaHoaDon.Text.Length == 0)
                {
                    MessageBox.Show(Common.MSG.MSG13(lbMaHoaDon.Text), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    txtMaHoaDon.Focus();
                    return;
                }

                checksua = false;
                mahanghoa = txtMaHangHoa.Text.ToUpper();
                if (chitiethoadonnhap == null)
                {
                    Entities.ChiTietHoaDonNhap ct = new Entities.ChiTietHoaDonNhap();
                    ct.HanhDong = "4";
                    ct.MaHoaDonNhap = mahoadon;
                    ct.MaHangHoa = "";
                    chitiethoadonnhap = new TimKiem.frmHangHoaNhapKho().HienThi(ct);
                }
                bool kt = false;
                foreach (Entities.ChiTietHoaDonNhap item in chitiethoadonnhap)
                {
                    if (item.MaHangHoa.ToUpper() == mahanghoa)
                    {
                        txtTenHangHoa.Text = item.TenHangHoa;
                        mahoadon = item.MaHoaDonNhap;
                        CheckSoLuongConLai();
                        txtSoLuong.Focus();
                        cthdn = item;
                        kt = true;
                        break;
                    }
                }
                if (!kt)
                {
                    MessageBox.Show(Common.MSG.MSG27(lbMaHangHoa.Text), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    txtTenHangHoa.Text = "";
                    return;
                }
            }
            catch
            {
            }
        }

        void XuLyEnter_SoLuong()
        {
            try
            {
                if (tralaincc != null)
                    if (tralaincc.ThanhToanNgay != "0")
                    {
                        if (MessageBox.Show("Đã thanh toán rồi, thanh toán sẽ = 0 - Bạn chắc chắn muốn thêm?", Common.MSG.TieuDe, MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                        {

                            tralaincc.ThanhToanNgay = "0";
                            AddRow();
                            tralaincc.TienBoiThuong = txtTongTien.Text;
                        }
                        return;
                    }
                AddRow();
            }
            catch
            {
            }
        }

        void dgvHienThi_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            SuaRow();
        }

        void dgvHienThi_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (hanhDong != Common.Constants.Insert)
                return;
            try
            {
                i = e.RowIndex;
                if (i < 0)
                    return;
                if (dgvHienThi.RowCount == 0)
                    return;
                save = ((Entities.ChiTietTraLaiNCC[])dgvHienThi.DataSource)[i];
            }
            catch
            {
            }

        }

        void btnTimNCC_Click(object sender, EventArgs e)
        {
            ThemNhaCungCap();
        }

        void btnThemGV_Click(object sender, EventArgs e)
        {
            XuLyEnter_SoLuong();
        }

        void btnThanhToan_Click(object sender, EventArgs e)
        {
            ThanhToan();
        }

        void txtTyLeTinh_TextChanged(object sender, EventArgs e)
        {
            TextBox temp = (TextBox)sender;
            int vt = temp.SelectionStart;
            string str = new string(temp.Text.ToList<char>().Where(c => char.IsNumber(c)).ToArray<char>());

            temp.Text = str;

            temp.SelectionStart = vt;
        }

        void btnThoat_Click(object sender, EventArgs e)
        {
            Thoat();
        }

        void frmXuLy_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!checkClose)
                if (MessageBox.Show(Common.MSG.MSG2(), Common.MSG.TieuDe, MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                    e.Cancel = checkClose;
                else
                    e.Cancel = !checkClose;
            else
            {
                GetData(kiemtra);
            }
        }

        void txtMaHangHoa_Click(object sender, EventArgs e)
        {
            txtMaHangHoa.SelectAll();
        }
        #endregion
    }
}
#endregion